﻿var eraserActive = false;

function SetBoundaries() {
    
    $('.selectable').removeClass('selectable-Left');
    $('.selectable').removeClass('selectable-Right');
    $('.selectable').removeClass('selectable-Top');
    $('.selectable').removeClass('selectable-Bottom');

    var firstRow = 99;
    var lastRow = 0;
    var firstCol = 99;
    var lastCol = 0;

    $('.selectable-selected').each(function () {
        var vert = parseInt($(this).attr('vertical'), 10);
        var horz = parseInt($(this).attr('horizontal'), 10);
        if (vert < firstRow) {
            firstRow = vert;
        }
        if (vert > lastRow) {
            lastRow = vert;
        }
        if (horz < firstCol) {
            firstCol = horz;
        }
        if (horz > lastCol) {
            lastCol = horz;
        }
    });

    if (lastRow > 0) {
        $('.hor' + firstCol).addClass('selectable-Left');
        $('.hor' + lastCol).addClass('selectable-Right');
        $('.ver' + firstRow).addClass('selectable-Top');
        $('.ver' + lastRow).addClass('selectable-Bottom');
    }
}

function ToggleSelection(el) {
    var isMouseDown = true;
    if (eraserActive) {
        $(el).addClass('selectable-deselecting');
    } else {
        $(el).addClass('selectable-selecting');
    }

    $('.selectable').hover(function () {
        if (isMouseDown) {
            if (eraserActive) {
                $(this).addClass('selectable-deselecting');
            } else {
                $(this).addClass('selectable-selecting');
            }
        }
    }, function () {

    });

    $(document).mouseup(function () {
        if (isMouseDown) {
            isMouseDown = false;
            $('.selectable-selecting').addClass('selectable-selected');
            $('.selectable-selecting').removeClass('selectable-selecting');
            $('.selectable-deselecting').removeClass('selectable-selected');
            $('.selectable-deselecting').removeClass('selectable-selecting');
            $('.selectable-deselecting').removeClass('selectable-deselecting');
            SetBoundaries();
        }
    });
}

function GetActiveCellString() {
    var result = '';
    $('.selectable-selected').each(function () {
        result += $(this).attr('cell') + ',';
    });
    return result;
}

function GetSelectedSizesString() {
    var result = '';
    $('#selectedSizes').children().each(function () {
        result += $(this).attr('length') + '-' + $(this).attr('width') + ',';
    });
    return result;
}

function RegisterCalculationLoadedEvents() {
    $('#calculationcancel').click(function (e) {
        e.preventDefault();
        $('#SizeSelectionContainer').slideUp(500, function () {
            $('#SizeSelectionContainer').empty();
        });
    });

    $('.calculationSelect').click(function (e) {
        e.preventDefault();
        $('#selectedPortions').text($(this).attr('portions'));
        $('#selectedLength').text($(this).attr('length'));
        $('#selectedWidth').text($(this).attr('width'));
        $('#selectedSizes').html($(this).parent().parent().children().first().children('.sizeshtml'));
        $('#portionsInputContainer').slideUp(250, function () {
            $('#SizeSelectionContainer').slideUp(250, function () {
                $('#SizeSelectionContainer').empty();
                $('#SelectedSizeContainer').slideDown(500);
            });
        });
    });
}

function HandleFailedSave(error) {
    $('#SaveErrorMessage').text(error);
    $('#SaveError').slideDown(250);
    setTimeout(function () {
        $('#SaveError').slideUp(250);
    }, 5000);
    $('#addSpinner').fadeOut(100);
}

function ApplySizesToCake() {
    $('#addSpinner').fadeIn(100);
    var data = {
            OrderId: $('#OrderId').val(),
            ComponentId: $('#ComponentId').val(),
            Portions: $('#selectedPortions').text(),
            OverallLength: $('#selectedLength').text(),
            OverallWidth: $('#selectedWidth').text(),
            SelectedCellString: GetActiveCellString(),
            SizesString: GetSelectedSizesString()
        };
        $.ajax({
            url: '/order/ApplyShapeBuilderToCake',
            type: "POST",
            data: data,
            dataType: "json",
            success: function (result) {
                if (result.Success) {
                    window.location = '/order/edit/' + $('#OrderId').val();
                } else {
                    HandleFailedSave(result.ErrorMessage);
                }
            },
            fail: function () {
                HandleFailedSave("Failed to save sizes to cake");
            }
        });
}

$(document).ready(function () {

    $('.selectable').mousedown(function () {
        ToggleSelection(this);
    });

    $('#erase').click(function () {
        if (eraserActive) {
            $(this).text('Enable Eraser');
            eraserActive = false;
        } else {
            $(this).text('Disable Eraser');
            eraserActive = true;
        }
    });

    $('#clearAll').click(function () {
        $('.selectable-selected').removeClass('selectable-selected');
        $('.selectable').removeClass('selectable-Left');
        $('.selectable').removeClass('selectable-Right');
        $('.selectable').removeClass('selectable-Top');
        $('.selectable').removeClass('selectable-Bottom');
    });

    $('#calculateParty').click(function () {
        $('#SelectedSizeContainer').slideUp(100);
        var data = { Portions: $('#Portions').val(), IsParty: true, SelectedCellString: GetActiveCellString() };
        PostReturningHtml("/order/CalculateShapeBuilderSizes", data, $('#SizeSelectionContainer'), function () {
            RegisterCalculationLoadedEvents();
        });
    });

    $('#calculateWedding').click(function () {
        $('#SelectedSizeContainer').slideUp(100);
        var data = { Portions: $('#Portions').val(), IsParty: false, SelectedCellString: GetActiveCellString() };
        PostReturningHtml("/order/CalculateShapeBuilderSizes", data, $('#SizeSelectionContainer'), function () {
            RegisterCalculationLoadedEvents();
        });
    });

    $('#applyToCake').click(function () {
        ApplySizesToCake();
    });

    $('#cancelApplyToCake').click(function () {
        $('#SelectedSizeContainer').slideUp(250, function () {
            $('#portionsInputContainer').slideDown(500);
        });
    });

    SetBoundaries();
});